<?php

/**
 * Вся админка здесь
 *
 * @author kingop
 */
class AdminController extends CustomControllerAction {

    public $count_user = 0;
    public $count_request = 0;
    public $configObj = null;
    public $seoConfigObj = null;

    public function preDispatch() {
        parent::preDispatch();

        $this->count_user = DatabaseObject_User::GetUsersCount($this->db, array('where' => 'isApproved = 0'));
        $this->view->count_user = $this->count_user;
        $this->count_request = DatabaseObject_Requests::GetUnknownCount($this->db);
        $this->view->count_request = $this->count_request;

        $this->configObj = DatabaseObject_Config::GetConfigObject($this->db);
        $this->seoConfigObj = DatabaseObject_SeoConfig::GetConfigObject($this->db);
    }

    //------------------------- служебные функции ------------------------------

    public function updateConfig($name, $value) {
        return DatabaseObject_Config::UpdateConfigValue($this->db, $name, $value);
    }

    //------------------------- конец служебных функций ------------------------

    public function indexAction() {
         $this->view->page_title = "Администраторский раздел";
        $stat = array(
            'tenders' => 0,
            'archive' => 0,
            'live' => 0,
            'requests' => 0,
            'approved_requests' => 0,
            'declined_requests' => 0,
            'users' => 0,
            'last_user' => null,
            'projects' => 0
        );

        // количество тендеров
        $stat['tenders'] = DatabaseObject_Tender::GetCount($this->db);
        // количество активных тендеров
        $stat['live'] = DatabaseObject_Tender::GetLiveCount($this->db);
        // количество тендеров в архиве
        $stat['archive'] = DatabaseObject_Tender::GetArchiveCount($this->db);
        // количество заявок
        $stat['requests'] = DatabaseObject_Requests::GetRequestsCount($this->db);
        // количество принятых заявок
        $stat['approved_requests'] = DatabaseObject_Requests::GetApprovedCount($this->db);
        // количество отклоненных заявок
        $stat['declined_requests'] = DatabaseObject_Requests::GetDeclinedCount($this->db);
        // количество непросмотренных заявок
        $stat['unknown_requests'] = DatabaseObject_Requests::GetUnknownCount($this->db);
        // количество пользователей
        $stat['users'] = DatabaseObject_User::GetUsersCount($this->db, array());
        // последний зарегистрированный пользователь
        $stat['last_user'] = DatabaseObject_User::GetUsers($this->db, array('limit' => '1', 'order' => 'id desc'));
        // количество проектов
        $stat['projects'] = DatabaseObject_Project::GetCount($this->db);

        $this->view->stat = $stat;
    }

    //------------------------ начало работы с тендерами------------------------

    public function tendersAction() {

          $this->view->page_title = "Тендеры";
          if ($this->getRequest()->isPost()) {
            
            $_SESSION['filter_cat'] = $this->getRequest()->getPost('cats_filter');
            $_SESSION['filter_project'] = $this->getRequest()->getPost('projects_filter');
            $_SESSION['filter_archive'] = $this->getRequest()->getPost('archive_filter');
            $_SESSION['search'] = $this->getRequest()->getPost('search');
        }elseif (!$this->getRequest()->getParam('p')){
            $_SESSION['filter_cat'] = array();
            $_SESSION['filter_project'] = array();
            $_SESSION['filter_archive'] = '2';
            $_SESSION['search'] = '';
        }
        
        if (($_GET['sort']) && ($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['tender_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['tender_sort'])) {
            $temp = explode(' ', $_SESSION['tender_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'name';
            $order = 'asc';
            $_SESSION['tender_sort'] = $sort . ' ' . $order;
        }
        $options = array('order' => 'p.' . $sort . ' ' . $order);
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['tenders_per_page_admin'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Tender::GetFilterCount($this->db, array('idCat' => $_SESSION['filter_cat'], 'idProject' => $_SESSION['filter_project'], 'archive' => $_SESSION['filter_archive'], 'search' => $_SESSION['search']), array('order' => $_SESSION['tender_sort'])) / $limit);
        $tender = DatabaseObject_Tender::FilterTenders($this->db, array('idCat' => $_SESSION['filter_cat'], 'idProject' => $_SESSION['filter_project'], 'archive' => $_SESSION['filter_archive'],'search' => $_SESSION['search']), array('order' => $_SESSION['tender_sort'], 'limit' => $limit, 'offset' => $offset));

        $cats = DatabaseObject_Categories::GetCategories($this->db);
        $project = DatabaseObject_Project::GetProjects($this->db);
        $this->view->cats_filter = $_SESSION['filter_cat'];
        $this->view->projects_filter = $_SESSION['filter_project'];
        $this->view->archive_filter = $_SESSION['filter_archive'];
        $this->view->tenders = $tender;
        $this->view->cats = $cats;
        $this->view->projects = $project;
        $this->view->option_sort = $option_sort;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->pages = $pages;
        $this->view->page = $page;
    }

    public function addtenderAction() {
          $this->view->page_title = "Добавление тендера";
        $request = $this->getRequest();
        $fp = new FormProcessor_TenderAdd($this->db);

        $cats = DatabaseObject_Categories::GetCategories($this->db);
        $projects = DatabaseObject_Project::GetProjects($this->db);
        $validate = $request->isXmlHttpRequest();

        if ($request->isPost()) {
            if ($validate) {
                $fp->validateOnly(true);
                $fp->process($request);
            } else if ($fp->process($request)) {
                $id = $fp->tender->getId();

                // отправим пользователям уведомление о новом тендере в интересующей их категории
                $view_tender_link = '<a href="http://' . $_SERVER['SERVER_NAME'] . '/tender/' . $id . '">Перейти к тендеру</a>';
                $users = DatabaseObject_User::GetUsers($this->db, array('where id in (' . DatabaseObject_UsersCats::GetUsersIdsByCat($this->db, $fp->tender->idCat) . ')'));
                $subject = $this->configuration['email_new_tender_subject'];
                $text = preg_replace('/%viewlink%/', $view_tender_link, $this->configuration['email_new_tender_text']);
                $text = preg_replace('/%tender%/', $fp->tender->name, $text);

                /* Для отправки HTML-почты вы можете установить шапку Content-type. */
                $headers= "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=utf-8\r\n";

                /* дополнительные шапки */
                $headers .= "From: Герц. Тендерная площадка <administrator@tenders.gerc.dn.ua>\r\n";
                
                foreach ($users as $user) {
                    mail($user->email, $subject, $text, $headers);
                }

                $message = sprintf('Добавлен тендер "%s" администратором "%s"', $fp->tender->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'addtendercomplete'));
            }
        }

        if ($validate) {
            $json = array(
                'errors' => $fp->getErrors()
            );
            $this->sendJson($json);
        } else {
            $this->view->fp = $fp;
        }

        $this->view->cats = $cats;
        $this->view->projects = $projects;
        $this->view->fp = $fp;
    }

    public function edittenderAction() {
          $this->view->page_title = "Редактирование тендера";
        $id = $this->getRequest()->getParam('id');

        $fp = new FormProcessor_TenderEdit($this->db, $id);

        if ($this->getRequest()->isPost()) {
            if ($fp->process($this->getRequest())) {
                $message = sprintf('Изменена информация о тендере "%s" администратором "%s"', $fp->tender->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'edittendercomplete'));
            }
        }

        $this->view->cats = DatabaseObject_Categories::GetCategories($this->db);
        $this->view->projects = DatabaseObject_Project::GetProjects($this->db);
        $this->view->fp = $fp;
    }

    public function addfileAction() {

        ////Загрузка 
        if ($_FILES['upload']) {
            $upl = @$_FILES['upload'];
            $ufilename = $upl['name'];
            $path = DatabaseObject_TendersFiles::GetUploadDirectory();
            $filename = $ufilename;
            $file = $path . '/' . $filename;
            if (move_uploaded_file($_FILES['upload']['tmp_name'], $file)) {
                echo $filename;
            } else {
                echo "error";
            }
        }
        exit;
    }

    public function uploaddateAction() {
        $id = $this->getRequest()->getPost(id);
        $tender = new DatabaseObject_Tender($this->db);
        $tender->load($id);
        $date = $this->getRequest()->getPost(date);
        if (DatabaseObject_Tender::EndDateUpload($this->db, $id, $date)) {
            
            $message = sprintf('Тендер "%s" продлен до %s администратором "%s"', $tender->name, $date, Zend_Auth::getInstance()->getIdentity()->login);

            $this->writeLog($message);
            
            echo 'ok';
        }
        else
            echo 'Тендер не продлен';

        exit;
    }

    public function deletefileAction() {

        ////Загрузка 
        $filename = $this->getRequest()->getPost(id);
        $id = explode('-', $filename);
        echo $id['0'];
        $path = DatabaseObject_TendersFiles::GetUploadDirectory();
        $file = $path . '/' . $filename;
        DatabaseObject_TendersFiles::DeleteTenderFileID($this->db, $id['0']);
        if (file_exists($file)) {
            if (unlink($file)) {

                echo 'yes';
            } else {
                echo "error";
            }
        } else {
            echo 'error1';
        }
        exit;
    }

    public function archivetenderAction() {
        $id = $this->getRequest()->getParam('id');
        $tender = new DatabaseObject_Tender($this->db);
        if (!$tender->load($id)) {
            echo 'Тендер не найден';
            exit;
        }
        if ($tender->archive == 0) {
            $tender->archive = 1;
            $tender->save();
            $message = sprintf('Тендер "%s" был отправлен в архив администратором "%s"', $tender->name, Zend_Auth::getInstance()->getIdentity()->login);

            $this->writeLog($message);            
        } else {
            $tender->archive = 0;
            $tender->save();
            $message = sprintf('Тендер "%s" вернул из архива администратор "%s"', $tender->name, Zend_Auth::getInstance()->getIdentity()->login);

            $this->writeLog($message);
        }
        echo "ok";
        exit;
        // $this->_redirect($this->getUrl('tenders', 'admin'));
    }

    public function deletetenderAction() {
        $id = $this->getRequest()->getParam('id');
        $tender = new DatabaseObject_Tender($this->db);
        if (!$tender->load($id)) {
            echo 'Такой тендер не найден';
            exit;
        }

        $tmp = $tender->delete();
        if (!$tmp) {
            echo "Ошибка удаления";
            exit;
        }

        $tender_file = new DatabaseObject_TendersFiles($this->db);
        $tender_file->load($id, 'idTender');
        
        $message = sprintf('Тендер "%s" был удален администратором "%s"', $tender->name, Zend_Auth::getInstance()->getIdentity()->login);

        $this->writeLog($message);
            
        echo "ok";
        exit;
        // $this->_redirect($this->getUrl('tenders', 'admin'));
    }

    public function tendermembersAction() {
        $id = $this->getRequest()->getParam('id');
        $winner  = DatabaseObject_TendersWinners::GetWinner($this->db, $id);
      
        $requests = DatabaseObject_Requests::GetRequests($this->db, array('where' => 'idTender = ' . $id . ' and isApproved = 1'));
          print_r($requests->winner);
        $this->view->requests = $requests;
    }

    public function finishtenderAction() {
        $idRequest = $this->getRequest()->getParam('id');
        $request->load($idRequest);

        DatabaseObject_TendersWinners::FinishTender($this->db, $idRequest);
        
        $message = sprintf('Тендер "%s" был завершен администратором "%s"', $request->tender->name, Zend_Auth::getInstance()->getIdentity()->login);

        $this->writeLog($message);
        
        echo "ok";
        exit;
        //$this->_redirect($this->getUrl('tenders'));
    }

    //--------------------- работа с тендерами окончена ------------------------
    //--------------------- начало работы с категориями ------------------------

    public function categoriesAction() {

          $this->view->page_title = "Категории";
        if (($_GET['sort']) && ($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['project_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['project_sort'])) {
            $temp = explode(' ', $_SESSION['project_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'name';
            $order = 'asc';
            $_SESSION['project_sort'] = $sort . ' ' . $order;
        }
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['cats_per_page'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Categories::GetCount($this->db) / $limit);
        $category = DatabaseObject_Categories::GetCategories($this->db, array('order' => $_SESSION['project_sort'], 'limit' => $limit, 'offset' => $offset));

        $this->view->pages = $pages;
        $this->view->page = $page;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->categories = $category;
    }

    public function addcategoryAction() {
          $this->view->page_title = "Добавление категории";
        $request = $this->getRequest();
        $fp = new FormProcessor_CategoryAdd($this->db);


        $validate = $request->isXmlHttpRequest();

        if ($request->isPost()) {
            if ($validate) {
                $fp->validateOnly(true);
                $fp->process($request);
            } else if ($fp->process($request)) {
                $id = $fp->category->getId();
                $message = sprintf('Добавлена категория "%s" администратором "%s"', $fp->category->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                $this->_redirect($this->getCustomUrl(array(), 'addcategorycomplete'));
            }
        }

        if ($validate) {
            $json = array(
                'errors' => $fp->getErrors()
            );
            $this->sendJson($json);
        } else {
            $this->view->fp = $fp;
        }


        $this->view->fp = $fp;
    }

    public function editcategoryAction() {
          $this->view->page_title = "Редактирование категории";
        $id = $this->getRequest()->getParam('id');

        $fp = new FormProcessor_CategoryEdit($this->db, $id);

        if ($this->getRequest()->isPost()) {
            if ($fp->process($this->getRequest())) {
                
                $message = sprintf('Категория "%s" была отредктирована администратором "%s"', $fp->category->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'editcategorycomplete'));
            }
        }

        $this->view->fp = $fp;
    }

    public function deletecategoryAction() {
        $id = $this->getRequest()->getParam('id');
        $category = new DatabaseObject_Categories($this->db);
        if (!$category->load($id)) {
            echo 'Категория не найдена';
            exit;
        }
        if (!$category->delete()) {
            echo 'Ошибка удаления категории';
            exit;
        }
        
        $message = sprintf('Категория "%s" удалена администратором "%s"', $category->name, Zend_Auth::getInstance()->getIdentity()->login);

        $this->writeLog($message);
        
        echo 'ok';
        exit;
    }

    //--------------------- работа с категориями окончена ----------------------
    //--------------------- начало работы с проектами --------------------------

    public function projectsAction() {

        $this->view->page_title = "Проекты";
        if (($_GET['sort']) && ($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['project_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['project_sort'])) {
            $temp = explode(' ', $_SESSION['project_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'name';
            $order = 'asc';
            $_SESSION['project_sort'] = $sort . ' ' . $order;
        }
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['projects_per_page'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Project::GetCount($this->db) / $limit);
        $project = DatabaseObject_Project::GetProjects($this->db, array('order' => $_SESSION['project_sort'], 'limit' => $limit, 'offset' => $offset));

        $this->view->page = $page;
        $this->view->pages = $pages;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->projects = $project;
    }

    public function addprojectAction() {
        $this->view->page_title = "Добавление проекта";
        $request = $this->getRequest();
        $fp = new FormProcessor_ProjectAdd($this->db);


        $validate = $request->isXmlHttpRequest();

        if ($request->isPost()) {
            if ($validate) {
                $fp->validateOnly(true);
                $fp->process($request);
            } else if ($fp->process($request)) {
                $id = $fp->project->getId();
                
                $message = sprintf('Добавлен проект "%s" администратором "%s"', $fp->project->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'addprojectcomplete'));
            }
        }

        if ($validate) {
            $json = array(
                'errors' => $fp->getErrors()
            );
            $this->sendJson($json);
        } else {
            $this->view->fp = $fp;
        }


        $this->view->fp = $fp;
    }

    public function editprojectAction() {
        $this->view->page_title = "Редактирование проекта";
        $id = $this->getRequest()->getParam('id');

        $fp = new FormProcessor_ProjectEdit($this->db, $id);

        if ($this->getRequest()->isPost()) {
            if ($fp->process($this->getRequest())) {
                
                $message = sprintf('Проект "%s" был отредактирован администратором "%s"', $fp->project->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'editprojectcomplete'));
            }
        }

        $this->view->fp = $fp;
    }

    public function deleteprojectAction() {
        $id = $this->getRequest()->getParam('id');
        $project = new DatabaseObject_Project($this->db);
        if (!$project->load($id)) {
            echo 'Проект не найден';
            exit;
        }
        if (!$project->delete()) {
            echo 'Ошибка удаления проекта';
            exit;
        }
        
        $message = sprintf('Проект "%s" был удален администратором "%s"', $project->name, Zend_Auth::getInstance()->getIdentity()->login);

        $this->writeLog($message);
        
        echo 'ok';
        exit;
    }

    //---------------- работа с проектами окончена -----------------------------
    //------------------------- начало работы с пользователями -----------------

    public function usersAction() {
        $this->view->page_title = "Пользователи";
        if ($this->getRequest()->isPost()) {
            
            $_SESSION['filter_cat'] = $this->getRequest()->getPost('cats_filter');
            $_SESSION['filter_city'] = $this->getRequest()->getPost('city_filter');
            $_SESSION['filter_region'] = $this->getRequest()->getPost('region_filter');
            $_SESSION['filter_archive'] = $this->getRequest()->getPost('archive_filter');
            //$_SESSION['search'] = $this->getRequest()->getPost('search');
        }elseif (!$this->getRequest()->getParam('p')){
            $_SESSION['filter_cat'] = array();
            $_SESSION['filter_city'] = '0';
            $_SESSION['filter_region'] = '';
            $_SESSION['filter_archive'] = '2';
            //$_SESSION['search'] = '';
        }
        
         if (($_GET['sort'])&&($_GET['order']))  {$sort = $_GET['sort']; $order = $_GET['order']; $_SESSION['user_sort'] =  $sort.' '.$order; }
        elseif (!empty($_SESSION['user_sort'])){$temp = explode(' ',$_SESSION['user_sort']); $sort = $temp['0'] ; $order = $temp['1'];}
        else {$sort ='id'; $order ='desc'; $_SESSION['user_sort'] =  $sort.' '.$order; }
        $options = array('order'=> 'p.'.$sort.' '.$order);
         $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['projects_per_page'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_User::GetUsersCount($this->db, array('region'=>$_SESSION['filter_region'],'city' => $_SESSION['filter_city'],'idCat' => $_SESSION['filter_cat'], 'isApproved' => $_SESSION['filter_archive']), array('limit' => $limit, 'offset' => $offset)) / $limit);
        $users = DatabaseObject_User::FilterUsers($this->db, array('region'=>$_SESSION['filter_region'],'city' => $_SESSION['filter_city'],'idCat' => $_SESSION['filter_cat'], 'isApproved' => $_SESSION['filter_archive']),array('order' => $_SESSION['user_sort'], 'limit' => $limit, 'offset' => $offset));
      
        $cats = DatabaseObject_Categories::GetCategories($this->db);
        $this->view->pages = $pages;
        $this->view->page = $page;
        $this->view->cats_filter = $_SESSION['filter_cat'];
        $this->view->city_filter = $_SESSION['filter_city'];
        $this->view->region_filter = $_SESSION['filter_region'];
        $this->view->archive_filter = $_SESSION['filter_archive'];
        $this->view->cats = $cats;
        $region = DatabaseObject_Region::GetRegion($this->db);
        if ($filter_region !='' && $filter_region != '0')$cities = DatabaseObject_Cities::GetCities($this->db,$filter_region);
     // echo '<pre>';  print_r($cities);   echo '</pre>'; //
        $this->view->option_sort = $option_sort;
        $this->view->regions = $region;
        if (count($cities)> 0) $this->view->cities= $cities;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->users = $users;
        
        
    }
    

    public function edituserAction() {
        $this->view->page_title = "Редактирование пользователей";
        $id = $this->getRequest()->getParam('id');

        $cats = DatabaseObject_Categories::GetCategories($this->db);

        $fp = new FormProcessor_EditUser($this->db, $id);

        if ($this->getRequest()->isPost()) {
            if ($fp->process($this->getRequest())) {
                
                $message = sprintf('Личные данные пользователя "%s" были отредактированы администратором "%s"', $fp->user->login, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'editusercomplete'));
            }
        }
        if ($this->getRequest()->getParam('region')) { $region_id = $this->getRequest()->getParam('region');$this->view->cities = DatabaseObject_Cities::GetCities($this->db, $region_id);}
        $this->view->regions = DatabaseObject_Region::GetRegion($this->db);

        $this->view->cats = $cats;
        $this->view->fp = $fp;
    }

    public function deleteuserAction() {
        $id = $this->getRequest()->getParam('id');

        $user = new DatabaseObject_User($this->db);
        if (!$user->load($id)) {
            echo 'Такой пользователь не найден';
            exit;
        };
        $email = $user->email;
        if (!$user->delete()) {
            echo 'Ошибка удаления';
            exit;
        };
        
        // отправим пользователю уведомление о том, что его аккаунт одобрен
        $text = $this->configuration['email_delete_account_text'];
        $subject = $this->configuration['email_delete_account_subject'];
        
        /* Для отправки HTML-почты вы можете установить шапку Content-type. */
        $headers= "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=utf-8\r\n";

        /* дополнительные шапки */
        $headers .= "From: Герц. Тендерная площадка <administrator@tenders.gerc.dn.ua>\r\n";
        
        mail($email, $subject, $text, $headers);
        
        $message = sprintf('Пользователь "%s" был удален администратором "%s"', $user->login, Zend_Auth::getInstance()->getIdentity()->login);

        $this->writeLog($message);
        
        echo 'ok';
        exit;
        // $this->_redirect($this->getUrl('users'));
    }

public function approveuserAction() {
        $id = $this->getRequest()->getParam('id');

        $user = new DatabaseObject_User($this->db);
        $user->load($id);
        if ($user->isApproved == 1) {
            $user->isApproved = 0;
            $user->save();
            // отправим пользователю уведомление о том, что его аккаунт заблокирован
            $text = $this->configuration['email_ban_text'];
            $subject = $this->configuration['email_ban_subject'];
        
            /* Для отправки HTML-почты вы можете установить шапку Content-type. */
            $headers= "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=utf-8\r\n";

            /* дополнительные шапки */
            $headers .= "From: Герц. Тендерная площадка <administrator@tenders.gerc.dn.ua>\r\n";
            
            mail($user->email, $subject, $text, $headers);
            
            $message = sprintf('Пользователь "%s" был заблокирован администратором "%s"', $user->login, Zend_Auth::getInstance()->getIdentity()->login);

            $this->writeLog($message);
        } else {
            $user->isApproved = 1;
            $user->save();
            // отправим пользователю уведомление о том, что его аккаунт одобрен
            $text = preg_replace('/%loginlink%/', '<a href="http://' . $_SERVER['SERVER_NAME'] . '/account/login">Выполнить вход</a>', $this->configuration['email_approve_text']);
            $subject = $this->configuration['email_approve_subject'];

            /* Для отправки HTML-почты вы можете установить шапку Content-type. */
            $headers= "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=utf-8\r\n";

            /* дополнительные шапки */
            $headers .= "From: Герц. Тендерная площадка <administrator@tenders.gerc.dn.ua>\r\n";
            
            mail($user->email, $subject, $text, $headers);
            
            $message = sprintf('Пользователь "%s" был одобрен администратором "%s"', $user->login, Zend_Auth::getInstance()->getIdentity()->login);

            $this->writeLog($message);
        }
        
        
        
        echo 'ok';
        exit;

        //$this->_redirect($this->getUrl('users'));
    }
    public function banuserAction() {
        $id = $this->getRequest()->getParam('id');

        $user = new DatabaseObject_User($this->db);
        $user->load($id);

        $user->isApproved = 0;
        $user->save();
        
        // отправим пользователю уведомление о том, что его аккаунт заблокирован
        $text = $this->configuration['email_ban_text'];
        $subject = $this->configuration['email_ban_subject'];
        
        /* Для отправки HTML-почты вы можете установить шапку Content-type. */
        $headers= "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=utf-8\r\n";

        /* дополнительные шапки */
        $headers .= "From: Герц. Тендерная площадка <administrator@tenders.gerc.dn.ua>\r\n";
        
        mail($user->email, $subject, $text, $header);

        $this->_redirect($this->getUrl('users'));
    }

    //------------------------- конец работы с пользователями ------------------
    //------------------------- начало работы с заявками -----------------------

    public function requestsAction() {
        $this->view->page_title = "Заявки";
          if ($this->getRequest()->isPost()) {
            
            $_SESSION['filter_cat'] = $this->getRequest()->getPost('cats_filter');
            $_SESSION['filter_project'] = $this->getRequest()->getPost('projects_filter');
            $_SESSION['filter_user'] = $this->getRequest()->getPost('users_filter');
            $_SESSION['filter_archive'] = $this->getRequest()->getPost('archive_filter');
            //$_SESSION['search'] = $this->getRequest()->getPost('search');
        }elseif (!$this->getRequest()->getParam('p')){
            $_SESSION['filter_cat'] = array();
            $_SESSION['filter_project'] = array();
            $_SESSION['filter_user'] = array();
            $_SESSION['filter_archive'] = '2';
            //$_SESSION['search'] = '';
        }
        
        if (($_GET['sort']) && ($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['request_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['request_sort'])) {
            $temp = explode(' ', $_SESSION['request_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'dtime';
            $order = 'desc';
            $_SESSION['request_sort'] = $sort . ' ' . $order;
        }
        
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['requests_per_page'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Requests::GetRequestsCountFilter($this->db, array('idCat' => $_SESSION['filter_cat'], 'idProject' => $_SESSION['filter_project'], 'idUser' => $_SESSION['filter_user'], 'isApproved' => $_SESSION['filter_archive'])) / $limit);
        
        
        $requests = DatabaseObject_Requests::FilterRequests($this->db, array('idCat' => $_SESSION['filter_cat'], 'idProject' => $_SESSION['filter_project'], 'idUser' => $_SESSION['filter_user'], 'isApproved' => $_SESSION['filter_archive']), array('order' => $_SESSION['request_sort'], 'limit' => $limit, 'offset' => $offset));
        // $requests = DatabaseObject_Requests::FilterRequests($this->db, array('where' => 'isDeleted = 0'));
        $cats = DatabaseObject_Categories::GetCategories($this->db);
        $project = DatabaseObject_Project::GetProjects($this->db);
        $user = DatabaseObject_User::GetUsers($this->db);
       
        $this->view->cats_filter = $_SESSION['filter_cat'];
        $this->view->projects_filter = $_SESSION['filter_project'];
        $this->view->users_filter = $_SESSION['filter_user'];
        $this->view->archive_filter = $_SESSION['filter_archive'];
        $this->view->tenders = $tender;
        $this->view->cats = $cats;
        $this->view->users = $user;
        $this->view->projects = $project;
        $this->view->requests = $requests;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->page = $page;
        $this->view->pages = $pages;
    }

    public function viewrequestAction() {
        $this->view->page_title = "Просмотр заявки";
        $id = $this->getRequest()->getParam('id');

        $request = new DatabaseObject_Requests($this->db);
        $request->load($id);
        $request->files = DatabaseObject_RequestFiles::GetRequestsFiles($this->db, $id);
        $this->view->request = $request;
    }

    public function approverequestAction() {
        $id = $this->getRequest()->getParam('id');

        $request = new DatabaseObject_Requests($this->db);
        if (!$request->load($id)) {
            echo 'Заявка не найдена';
            exit;
        };
        $request->isApproved = 1;
        if (!$request->save()) {
            echo 'Ошибка сохранения заявки';
            exit;
        };

        // отправим пользователю уведомление об успешно принятой заявке
        $text = $this->configuration['email_accept_request_text'];
        $subject = $this->configuration['email_accept_request_subject'];

        $view_request_link = '<a href="http://' . $_SERVER['SERVER_NAME'] . '/account/viewrequest/' . $request->getId() . '">Просмотреть заявку</a>';

        $text = preg_replace('/%viewlink%/', $view_request_link, $text);
        $text = preg_replace('/%tender%/', $request->tender->name, $text);

        /* Для отправки HTML-почты вы можете установить шапку Content-type. */
        $headers= "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=utf-8\r\n";

        /* дополнительные шапки */
        $headers .= "From: Герц. Тендерная площадка <administrator@tenders.gerc.dn.ua>\r\n";
        
        mail($request->user->email, $subject, $text, $headers);

        $message = sprintf('Заявка пользователя "%s" на участие в тендере "%s" была одобрена администратором "%s"', $request->user->login, $request->tender->name, Zend_Auth::getInstance()->getIdentity()->login);

        $this->writeLog($message);
        
        echo 'ok';
        exit;
        //$this->_redirect($this->getUrl('requests'));
    }

    public function deleterequestAction() {
        $id = $this->getRequest()->getParam('id');

        $request = new DatabaseObject_Requests($this->db);
        $request->load($id);
        if ($this->getRequest()->isPost())
            if (strlen($this->getRequest()->getPost('deleteReason')) > 0) {
                $request->isDeleted = 1;
                $request->isApproved = 0;
                $request->deleteReason = $this->getRequest()->getPost('deleteReason');
                $request->save();

                // Отправим пользователю уведмление о том, что его заявка удалена
                $text = $this->configuration['email_decline_request_text'];
                $subject = $this->configuration['email_decline_request_subject'];

                $view_request_link = '<a href="http://' . $_SERVER['SERVER_NAME'] . '/account/request/edit/' . $request->getId() . '">Просмотреть заявку</a>';

                $text = preg_replace('/%viewlink%/', $view_request_link, $text);
                $text = preg_replace('/%tender%/', $request->tender->name, $text);

                /* Для отправки HTML-почты вы можете установить шапку Content-type. */
                $headers= "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=utf-8\r\n";

                /* дополнительные шапки */
                $headers .= "From: Герц. Тендерная площадка <administrator@tenders.gerc.dn.ua>\r\n";
                
                mail($request->user->email, $subject, $text, $headers);

                $message = sprintf('Заявка пользователя "%s" на участие в тендере "%s" была отклонена администратором "%s"', $request->user->login, $request->tender->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                echo 'ok';
                exit;
                // $this->_redirect($this->getUrl('requests'));
            }
    }

    //------------------------- конец работы с заявками ------------------------
    
    //------------------------- начало работы со страницами --------------------
    
    public function pagesAction() {
        $p_page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['pages_per_page'];
        $offset = ($p_page - 1) * $limit;
        $p_pages = ceil(DatabaseObject_Pages::GetCount($this->db) / $limit);
        
        $pages = DatabaseObject_Pages::GetPages($this->db, array('limit' => $limit, 'offset' => $offset));
        
        $this->view->p_page = $p_page;
        $this->view->p_pages = $p_pages;
        $this->view->pages = $pages;
    }
    
    public function addpageAction() {
        $this->view->page_title = "Добавление страницы";
        $request = $this->getRequest();
        $fp = new FormProcessor_PageAdd($this->db);


        $validate = $request->isXmlHttpRequest();

        if ($request->isPost()) {
            if ($validate) {
                $fp->validateOnly(true);
                $fp->process($request);
            } else if ($fp->process($request)) {
                
                $message = sprintf('Добавлена страница "%s" администратором "%s"', $fp->page->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'addpagecomplete'));
            }
        }

        if ($validate) {
            $json = array(
                'errors' => $fp->getErrors()
            );
            $this->sendJson($json);
        } else {
            $this->view->fp = $fp;
        }


        $this->view->fp = $fp;
    }
    
    public function editpageAction() {
        $id = $this->getRequest()->getParam('id');
        
        $page = new DatabaseObject_Pages($this->db);
        $page->load($id);
        $fp = new FormProcessor_PageEdit($this->db, $id);

        if ($this->getRequest()->isPost()) {
            if ($fp->process($this->getRequest())) {
                
                $message = sprintf('Страница "%s" была отредактирована администратором "%s"', $fp->page->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);
                
                $this->_redirect($this->getCustomUrl(array(), 'editpagecomplete'));
            }
        }

        $this->view->fp = $fp;
    }
    
    public function deletepagesAction() {
        $id = $this->getRequest()->getParam('id');
        $page = new DatabaseObject_Pages($this->db);
        if (!$page->load($id)) {
            echo 'Страница не найдена';
            exit;
        }
        if (!$page->delete()) {
            echo 'Ошибка удаления страницы';
            exit;
        }
        
        $message = sprintf('Страница "%s" была удалена администратором "%s"', $page->name, Zend_Auth::getInstance()->getIdentity()->login);

        $this->writeLog($message);
        
        echo 'ok';
        exit;
    }
    
    public function addpagecompleteAction() {
        
    }
    
    public function editpagecompleteAction() {
        
    }
    
    //------------------------- конец работы со страницами ---------------------
    
    //------------------------- начало работы с настройками --------------------

    public function configAction() {
        $this->view->page_title = "Настройки";
        if ($this->getRequest()->isPost()) {
            $configs = array_keys($this->configuration);
            foreach ($configs as $key) {
                $this->updateConfig($key, $this->getRequest()->getPost($key));
            }

            $message = sprintf('Настройки сайта были изменены администратором "%s"', Zend_Auth::getInstance()->getIdentity()->login);

            $this->writeLog($message);
            
            $this->_redirect($this->getUrl('configcomplete'));
        }

        $this->view->configObj = $this->configObj;
    }
    
    public function configcompleteAction() {
        // ничего не делаем, просто отображаем шаблон
    }

    //------------------------- конец работы с настройками ---------------------
    //------------------------- начало работы с глобальными настройками --------

    public function globalconfigAction() {
        $this->view->page_title = "Глобальные настройки";
        if (Zend_Auth::getInstance()->getIdentity()->type != 'globaladmin')
            $this->_redirect($this->getUrl('index'));

        if ($this->getRequest()->isPost()) {
            $configItem = new DatabaseObject_Config($this->db);
            $configItem->config_name = $this->getRequest()->getPost('config_name');
            $configItem->config_display_name = $this->getRequest()->getPost('config_display_name');
            $configItem->config_value = '';
            $configItem->config_type = $this->getRequest()->getPost('config_type');
            $configItem->config_description = $this->getRequest()->getPost('config_description');
            $configItem->save();

            $this->configObj = DatabaseObject_Config::GetConfigObject($this->db);
        }
        $this->view->configObj = $this->configObj;
    }
    
    public function seoconfigAction() {
        $this->view->page_title = "Настройки для SEO";
        if (Zend_Auth::getInstance()->getIdentity()->type != 'globaladmin')
            $this->_redirect($this->getUrl('index'));

        if ($this->getRequest()->isPost()) {
            $configItem = new DatabaseObject_SeoConfig($this->db);
            $configItem->config_name = $this->getRequest()->getPost('config_name');
            $configItem->display_config_name = $this->getRequest()->getPost('display_config_name');
            $configItem->config_value = '';
            $configItem->save();

            $this->seoConfigObj = DatabaseObject_SeoConfig::GetConfigObject($this->db);
        }
        $this->view->seoConfigObj = $this->seoConfigObj;
    }

    public function deleteconfigAction() {
        if (Zend_Auth::getInstance()->getIdentity()->type != 'globaladmin')
            $this->_redirect($this->getUrl('index'));

        $id = $this->getRequest()->getParam('id');

        $configItem = new DatabaseObject_Config($this->db);
        $configItem->load($id);
        $configItem->delete();

        $this->_redirect($this->getUrl('globalconfig'));
    }
    
    public function deleteseoconfigAction() {
        if (Zend_Auth::getInstance()->getIdentity()->type != 'globaladmin')
            $this->_redirect($this->getUrl('index'));

        $id = $this->getRequest()->getParam('id');

        $configItem = new DatabaseObject_SeoConfig($this->db);
        $configItem->load($id);
        $configItem->delete();

        $this->_redirect($this->getUrl('seoconfig'));
    }

    public function editconfigAction() {
        $this->view->page_title = "Редактирование настроек";
        if (Zend_Auth::getInstance()->getIdentity()->type != 'globaladmin')
            $this->_redirect($this->getUrl('index'));

        $id = $this->getRequest()->getParam('id');

        $configItem = new DatabaseObject_Config($this->db);
        $configItem->load($id);

        if ($this->getRequest()->isPost()) {
            $configItem->config_name = $this->getRequest()->getPost('config_name');
            $configItem->config_display_name = $this->getRequest()->getPost('config_display_name');
            $configItem->config_type = $this->getRequest()->getPost('config_type');
            $configItem->config_description = $this->getRequest()->getPost('config_description');
            $configItem->save();

            $this->_redirect($this->getUrl('globalconfig'));
        }

        $this->view->configItem = $configItem;
    }
    
    public function editseoconfigAction() {
        $this->view->page_title = "Редактирование настроек SEO";
        if (Zend_Auth::getInstance()->getIdentity()->type != 'globaladmin')
            $this->_redirect($this->getUrl('index'));

        $id = $this->getRequest()->getParam('id');

        $configItem = new DatabaseObject_SeoConfig($this->db);
        $configItem->load($id);

        if ($this->getRequest()->isPost()) {
            $configItem->config_name = $this->getRequest()->getPost('config_name');
            $configItem->display_config_name = $this->getRequest()->getPost('display_config_name');
            $configItem->save();

            $this->_redirect($this->getUrl('seoconfig'));
        }

        $this->view->seoConfigItem = $configItem;
    }
    
    public function logsAction() {
        $this->view->page_title = "Журнал событий";
        
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['admin_notes_per_page'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Logger::GetCount($this->db) / $limit);
        
        $logs = DatabaseObject_Logger::GetNotes($this->db, array('limit' => $limit, 'offset' => $offset, 'order' => 'time desc'));
        
        $this->view->logs = $logs;
        $this->view->page = $page;
        $this->view->pages = $pages;
    }

    //------------------------- конец работы с глобальными настройками ---------
    //------------------------- complete-функции -------------------------------
    
    public function addtendercompleteAction() {
        // ничего не делаем, просто показываем шаблон
    }
    
    public function edittendercompleteAction() {
        // ничего не делаем, просто показываем шаблон
    }
    
    public function addcategorycompleteAction() {
        // ничего не делаем, просто показываем шаблон
    }
    
    public function editcategorycompleteAction() {
        // ничего не делаем, просто показываем шаблон
    }
    
    public function addprojectcompleteAction() {
        // ничего не делаем, просто показываем шаблон
    }
    
    public function editprojectcompleteAction() {
        // ничего не делаем, просто показываем шаблон
    }
    
    public function editusercompleteAction() {
        // ничего не делаем, просто показываем шаблон
    }
    
    //------------------------- конец complete-функций -------------------------
}

?>
